import { memo, useCallback } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Form, message } from 'antd';
import * as yup from 'yup';
import { alphaNumericRegexString } from '@/constants/regexp';
import { useAuthStore } from '@/store/authStore';
import { yupResolver } from '@hookform/resolvers/yup';
import QueueAnim from 'rc-queue-anim';
import RxButton from '@/components/RxForm/RxButton';
import RxCaptchaInput from '@/components/RxForm/RxCaptchaInput';
import RxInput from '@/components/RxForm/RxInput';
import RxPassword from '@/components/RxForm/RxPassword';
import { useCaptchaApi } from '@/hooks/api/useAuthApi';
import { formatPhone } from '@/utils/format';

const schema = yup
  .object({
    username: yup.string().required(),
    password: yup.string().required(),
    code: yup.string().required(),
  })
  .required();

const defaultValues: API.LoginParams = {
  code: '',
  password: '',
  username: '',
};

const LoginForm: FC<PropsWithChildren<{ show?: boolean }>> = ({ show }) => {
  const { control, handleSubmit, resetField } = useForm<API.LoginParams>({
    resolver: yupResolver(schema),
    defaultValues,
    mode: 'all',
    criteriaMode: 'all',
  });
  const {
    login: { login, loading },
  } = useAuthStore();
  const { run, data } = useCaptchaApi();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const onsubmit: SubmitHandler<API.LoginParams> = useCallback((values) => {
    if (!values.username.includes('@')) {
      values.username = formatPhone(values.username);
    }
    login(values)
      .then(() => {
        const redirect = searchParams.get('redirect');
        if (redirect) {
          navigate(redirect);
        } else {
          navigate('/');
        }
      })
      .finally(() => {
        resetField('code');
        run();
      });
  }, []);
  const componentProps = {
    onFinish: handleSubmit(onsubmit),
    className: 'w-72 h-72',
  };
  return !show ? null : (
    <QueueAnim
      leaveReverse
      //@ts-ignore
      component={Form}
      componentProps={componentProps}
    >
      {show
        ? [
            <RxInput
              key={'username'}
              name={'username'}
              placeholder={'手机号/邮箱'}
              control={control}
            />,
            <RxPassword
              key={'password'}
              name={'password'}
              placeholder={'密码'}
              control={control}
            />,
            <RxCaptchaInput
              key={'code'}
              name={'code'}
              placeholder={'验证码'}
              control={control}
              data={data as string}
              onClick={run}
            />,
            <div key={'submit'}>
              <RxButton loading={loading} />
            </div>,
          ]
        : null}
    </QueueAnim>
  );
};

export default memo(LoginForm);
